<?php
namespace App\Event;

use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\Component\Singleton;
use EasySwoole\Utility\File;
use App\Console\TestConsole;

class AppEvent implements Event
{
    use Singleton;

    public static function initialize() {
        // self::loadConf(EASYSWOOLE_ROOT . '/Config');
        self::loadConf(EASYSWOOLE_ROOT . '/App/Conf');
        self::loadDB();
        // $instance = \EasySwoole\EasySwoole\Config::getInstance();
        // $options = $instance->getConf();
        // var_dump($options);

        // \EasySwoole\Console\ConsoleModuleContainer::getInstance()->set(new TestConsole());
        include_once EASYSWOOLE_ROOT . "/App/Common/function.php";//通用函数库
        // define('HTTP_ROOT', Config::getInstance()->getConf('web.WEB_URL'));
    }

    public static function mainServerCreate(EventRegister $register) {
    }

    public static function onRequest(Request $request, Response $response): bool {
        $_GET = $request->getSwooleRequest()->get ?? [];
        $_POST = $request->getSwooleRequest()->post ?? [];
        $_COOKIE = $request->getSwooleRequest()->cookie ?? [];
        $_FILES = $request->getSwooleRequest()->files ??[];
        $_SERVER = $request->getSwooleRequest()->server ?? [];
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void {
        unset($GLOBALS);
        unset($_GET);
        unset($_POST);
        unset($_SESSION);
        unset($_COOKIE);
    }

    public static function loadDB() {
        // 获得数据库配置
        $dbConf = Config::getInstance()->getConf('database');
        // 全局初始化
        // Db::setConfig($dbConf);
    }

    public static function loadConf($ConfPath) {
        $Conf  = Config::getInstance();
        $files = File::scanDirectory($ConfPath);
        if (!is_array($files)) {
            return;
        }
        foreach ($files['files'] as $file) {
            $data = require_once $file;
            $Conf->setConf(strtolower(basename($file, '.php')), (array)$data);
        }
    }
}
